package com.yaoweigroup.community.ui.shop;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.adapter.CommentAdapter;
import com.yaoweigroup.community.config.Common;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.enity.Comment;
import com.yaoweigroup.community.enity.ShopDetail;
import com.yaoweigroup.community.ui.bm.OrderSubmitActivity;
import com.yaoweigroup.community.ui.home.GroupDetailActivity.MyImageGetter;
import com.yaoweigroup.community.ui.home.PostDetailActivity.MyImageGetter.URLDrawable;
import com.yaoweigroup.community.util.BitmapHelp;
import com.yaoweigroup.community.util.DialogUtil;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.MD5;
import com.yaoweigroup.community.util.UtilHttp;

public class ShopDetailActivity extends Activity implements OnClickListener {

	private ImageView icon_iv;
	private TextView name_tv;
	private ImageButton add_ib;
	private ImageButton sub_ib;
	private TextView detail_num_tv;
	private TextView price_tv;
	private Button buy_btn;
	private RelativeLayout group_detail_rl;
	private RelativeLayout comment_rl;
	private ImageView detail_iv;
	private ImageView comment_iv;
	private RelativeLayout content_detail_rl;
	private RelativeLayout content_comment_rl;

	private TextView content_tv;
	private ListView listView;
	private ProgressBar progress;
	private TextView empty_tv;
	private RelativeLayout left_rl;
	private TextView max_num_tv;

	private ShopDetail detail;
	private BitmapUtils bitmapUtils;
	private BitmapDisplayConfig bigPicDisplayConfig;

	private List<Comment> list;
	private ObjectMapper mapper;
	private CommentAdapter adapter;

	public final int COMMENT_SUCCESS = 0x2210;
	public final int COMMENT_FAIL = COMMENT_SUCCESS + 1;
	public final int DETAIL_SUCCESS = COMMENT_SUCCESS + 2;
	public final int DETAIL_FAIL = COMMENT_SUCCESS + 3;

	private Dialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shop_detail);

		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		dialog = DialogUtil.createWaitDialog(this, "正在获取中...");
		list = new ArrayList<Comment>();
		adapter = new CommentAdapter(this, list);
		mapper = new ObjectMapper();
		icon_iv = (ImageView) findViewById(R.id.icon_iv);
		name_tv = (TextView) findViewById(R.id.name_tv);
		add_ib = (ImageButton) findViewById(R.id.add_ib);
		add_ib.setOnClickListener(this);
		sub_ib = (ImageButton) findViewById(R.id.sub_ib);
		sub_ib.setOnClickListener(this);
		detail_num_tv = (TextView) findViewById(R.id.detail_num_tv);
		price_tv = (TextView) findViewById(R.id.price_tv);
		buy_btn = (Button) findViewById(R.id.buy_btn);
		buy_btn.setOnClickListener(this);
		max_num_tv = (TextView) findViewById(R.id.max_num_tv);
		group_detail_rl = (RelativeLayout) findViewById(R.id.group_detail_rl);
		group_detail_rl.setOnClickListener(this);
		comment_rl = (RelativeLayout) findViewById(R.id.comment_rl);
		comment_rl.setOnClickListener(this);
		detail_iv = (ImageView) findViewById(R.id.detail_iv);
		comment_iv = (ImageView) findViewById(R.id.comment_iv);
		content_detail_rl = (RelativeLayout) findViewById(R.id.content_detail_rl);
		content_comment_rl = (RelativeLayout) findViewById(R.id.content_comment_rl);
		content_tv = (TextView) findViewById(R.id.content_tv);
		listView = (ListView) findViewById(R.id.listView);
		listView.setAdapter(adapter);
		progress = (ProgressBar) findViewById(R.id.progress);
		empty_tv = (TextView) findViewById(R.id.empty_tv);
		bitmapUtils = BitmapHelp.getBitmapUtils(this);
		bigPicDisplayConfig = new BitmapDisplayConfig();
		bigPicDisplayConfig.setLoadFailedDrawable(this.getResources()
				.getDrawable(R.drawable.bucket_no_picture));
		bigPicDisplayConfig.setLoadingDrawable(this.getResources().getDrawable(
				R.drawable.bucket_no_picture));
		detail = (ShopDetail) getIntent().getSerializableExtra("detail");
		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(this);
		if (detail != null) {
			String url = detail.getHeadimg();
			if (!url.startsWith("http")) {
				url += Urls.imgUrl + url;
			}
			bitmapUtils.display(icon_iv, url, bigPicDisplayConfig);
			name_tv.setText(detail.getName());
			price_tv.setText("¥" + detail.getPrice());
			content_tv.setText(Html.fromHtml(detail.getDes(),
					new MyImageGetter(this, content_tv), null));
			max_num_tv.setText("库存" + detail.getStocknumber() + "件");
			try {
				stockNum = Integer.parseInt(detail.getStocknumber());
			} catch (Exception e) {

			}
			obtainComment(detail.getPid());
		} else {
			String id = getIntent().getStringExtra("id");
			obtainDetail(id);
		}
	}

	private int num = 1;
	private int stockNum = 1;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.group_detail_rl:
			detail_iv.setVisibility(View.VISIBLE);
			comment_iv.setVisibility(View.GONE);
			content_detail_rl.setVisibility(View.VISIBLE);
			content_comment_rl.setVisibility(View.GONE);
			break;
		case R.id.comment_rl:
			detail_iv.setVisibility(View.GONE);
			comment_iv.setVisibility(View.VISIBLE);
			content_detail_rl.setVisibility(View.GONE);
			content_comment_rl.setVisibility(View.VISIBLE);
			break;
		case R.id.add_ib:
			num += 1;
			if (num > stockNum) {
				num = stockNum;
				Toast.makeText(this, "购买的数量 不能大于库存", 500).show();
				return;
			}

			detail_num_tv.setText(num + "");
			break;
		case R.id.sub_ib:
			num -= 1;
			if (num <= 0)
				num = 0;
			detail_num_tv.setText(num + "");
			break;
		case R.id.left_rl:
			finish();
			break;
		case R.id.buy_btn:
			if (num == 0) {
				Toast.makeText(this, "购买数量不能为0", 500).show();
				return;
			}
			if (stockNum == 0) {
				Toast.makeText(this, "亲 库存没货哦，请稍等哦", 500).show();
				return;
			}
			detail.setNum(num);
			Intent intent = new Intent(this, OrderSubmitActivity.class);
			intent.putExtra("type", 1);//
			intent.putExtra("detail", detail);
			startActivity(intent);
			break;
		}
	}

	private int pageNo = 1;
	private int pageSize = 10;

	private void obtainComment(int id) {
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("id", id + "");
		jsonUtil.add("pageNo", pageNo + "");
		jsonUtil.add("pageSize", pageSize + "");
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.getProductComment, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String data = obj.getString("data");
							if (state == 200) {
								list = mapper.readValue(data,
										new TypeReference<List<Comment>>() {
										});
								handler.sendEmptyMessage(COMMENT_SUCCESS);

							} else {
								handler.sendEmptyMessage(COMMENT_FAIL);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(COMMENT_FAIL);

							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
					}

				});
	}

	private void obtainDetail(String id) {
		dialog.show();
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("id", id);
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.getProductdetail, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String data = obj.getString("data");
							if (state == 200) {
								detail = mapper.readValue(data,
										new TypeReference<ShopDetail>() {
										});
								handler.sendEmptyMessage(DETAIL_SUCCESS);

							} else {
								handler.sendEmptyMessage(DETAIL_FAIL);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(DETAIL_FAIL);

							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(DETAIL_FAIL);
					}

				});
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			progress.setVisibility(View.GONE);
			switch (msg.what) {
			case COMMENT_FAIL:
				if (list.size() == 0)
					empty_tv.setVisibility(View.VISIBLE);
				break;
			case COMMENT_SUCCESS:
				if (list != null) {
					if (list.size() > 0) {
						empty_tv.setVisibility(View.GONE);
						adapter.setDataChange(list);
					} else {
						empty_tv.setVisibility(View.VISIBLE);
					}
				} else {
					empty_tv.setVisibility(View.VISIBLE);
				}
				break;
			case DETAIL_FAIL:
				dialog.dismiss();
				finish();
				Toast.makeText(ShopDetailActivity.this, "获取失败！", 500).show();
				break;
			case DETAIL_SUCCESS:
				dialog.dismiss();
				if (detail != null) {
					String url = detail.getHeadimg();
					if (!url.startsWith("http")) {
						url += Urls.imgUrl + url;
					}
					bitmapUtils.display(icon_iv, url, bigPicDisplayConfig);
					name_tv.setText(detail.getName());
					price_tv.setText("¥" + detail.getPrice());
					try {
						content_tv.setText(Html.fromHtml(detail.getDes(),
								new MyImageGetter(ShopDetailActivity.this,
										content_tv), null));
					} catch (Exception e) {

					}
					max_num_tv.setText("库存" + detail.getStocknumber() + "件");
					try {
						stockNum = Integer.parseInt(detail.getStocknumber());
					} catch (Exception e) {

					}
					obtainComment(detail.getPid());
				}
				break;
			}
		};
	};

	public class MyImageGetter implements ImageGetter {

		private Context context;
		private TextView tv;

		public MyImageGetter(Context context, TextView tv) {
			this.context = context;
			this.tv = tv;
		}

		@Override
		public Drawable getDrawable(String source) {
			// TODO Auto-generated method stub
			// 将source进行MD5加密并保存至本地
			if (!source.startsWith("http")) {
				source = "http://www.smartcity.sh" + source;
			}
			LogUtil.d("wxf", "source=" + source);
			String imageName = MD5.encode(source);
			String sdcardPath = Environment.getExternalStorageDirectory()
					.toString(); // 获取SDCARD的路径
			// 获取图片后缀名
			String[] ss = source.split("\\.");
			String ext = ss[ss.length - 1];

			// 最终图片保持的地址
			String savePath = sdcardPath + "/" + context.getPackageName() + "/"
					+ imageName + "." + ext;

			File file = new File(savePath);
			if (file.exists()) {
				// 如果文件已经存在，直接返回
				Drawable drawable = Drawable.createFromPath(savePath);
				if (drawable == null)
					return null;
				drawable.setBounds(0, 0, drawable.getIntrinsicWidth() * 3,
						drawable.getIntrinsicHeight() * 3);
				return drawable;
			}

			// 不存在文件时返回默认图片，并异步加载网络图片
			Resources res = context.getResources();
			URLDrawable drawable = new URLDrawable(
					res.getDrawable(R.drawable.bucket_no_picture));
			new ImageAsync(drawable).execute(savePath, source);
			return drawable;

		}

		private class ImageAsync extends AsyncTask<String, Integer, Drawable> {

			private URLDrawable drawable;

			public ImageAsync(URLDrawable drawable) {
				this.drawable = drawable;
			}

			@Override
			protected Drawable doInBackground(String... params) {

				InputStream in = null;// TODO Auto-generated method stub
				try {
					String savePath = params[0];
					String url = params[1];

					// 获取网络图片
					HttpGet http = new HttpGet(url);
					HttpClient client = new DefaultHttpClient();
					HttpResponse response = (HttpResponse) client.execute(http);
					BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(
							response.getEntity());
					in = bufferedHttpEntity.getContent();

					if (in == null)
						return drawable;

					File file = new File(savePath);
					String basePath = file.getParent();
					File basePathFile = new File(basePath);
					if (!basePathFile.exists()) {
						basePathFile.mkdirs();
					}
					file.createNewFile();
					FileOutputStream fileout = new FileOutputStream(file);
					byte[] buffer = new byte[4 * 1024];
					while (in.read(buffer) != -1) {
						fileout.write(buffer);
					}
					fileout.flush();
					Drawable mDrawable = Drawable.createFromPath(savePath);
					return mDrawable;

				} catch (Exception e) {
					try {
						if (in != null)
							in.close();
					} catch (Exception e2) {
						// TODO: handle exception
					}
				}
				return drawable;
			}

			@Override
			protected void onPostExecute(Drawable result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				if (result != null) {
					drawable.setDrawable(result);
					tv.setText(tv.getText()); // 通过这里的重新设置 TextView 的文字来更新UI
				}
			}

		}

		public class URLDrawable extends BitmapDrawable {

			private Drawable drawable = null;

			public URLDrawable(Drawable defaultDraw) {
				if (defaultDraw == null)
					return;
				setDrawable(defaultDraw);
			}

			private void setDrawable(Drawable nDrawable) {
				if (nDrawable == null)
					return;
				try {

					drawable = nDrawable;
					drawable.setBounds(0, 0, drawable.getIntrinsicWidth() * 2,
							drawable.getIntrinsicHeight() * 2);
					setBounds(0, 0, drawable.getIntrinsicWidth(),
							drawable.getIntrinsicHeight());
				} catch (Exception e) {

				}
			}

			@Override
			public void draw(Canvas canvas) {
				try {
					if (drawable != null) {
						drawable.draw(canvas);
					}
				} catch (StackOverflowError e) {

				}

			}
		}
	}
}
